﻿using GetData.webProductClass;
using jutehui.GetData;
using jutehui.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace GetData
{
    public class tsdxb
    {
        /// <summary>
        /// 天上掉馅饼 HTML信息 获取商品信息 并保存到数据库
        /// </summary>
        /// <returns></returns>
        public string GetSaleURL(string url, int navType)
        {
            var htmlText = CustomMethod.GetHtmlByHttpHelper(url);
            var productList = GetProductByRegexToHtml(htmlText, navType);
            if (productList == null || productList.Count < 1)
            {
                return "网络异常，未能获取数据";
            }
            // GetProductList(jsonStr, productList);//得到要插入数据库的数据
            //保存数据库
            DataTable dt = null;
            //转化成table插入
            string errorMsg = "";
            dt = CustomMethod.ListToDataTable<Product>(productList, "Product", ref errorMsg);
            if (dt == null || dt.Rows.Count < 1)
            {
                return errorMsg;
            }
            jutehui.BLL.Product bll = new jutehui.BLL.Product();
            string msg = "";

            if (bll.SaveTableData("Product", dt, out msg))
            {
                return "";
            }
            else //返回失败信息
            {
                return msg;
            }
        }
        /// <summary>
        /// 根据正则解析商品信息
        /// </summary>
        /// <param name="htmlText"></param>
        /// <param name="type">海购还是精选</param>
        /// <returns></returns>
        private List<Product> GetProductByRegexToHtml(string htmlText, int type)
        {
            List<Product> pList = new List<Product>();
            string productRegex = @" <div class=""con_left_cp con_left_cp1"">[\s\S]*?</a></div>\s+</div>";
            var list = CustomMethod.GetInfoByRegex(productRegex, htmlText, 0);
            if (list == null || list.Count < 1)
            {
                string msg = "天上掉馅饼：GetProductByRegex ，没有抓到匹配的商品，检查匹配规则。";
                CustomMethod.WriteLog(msg);
                return null;
            }
            ProductTypeEnum pEnum = new ProductTypeEnum();
            //每个商品匹配所有相关属性并赋值
            for (int index = 0; index < list.Count; index++)
            { 
                Product product = new Product();
                product.FromWeb = "天上掉馅饼";
                product.TypeId = type;
                try
                {
                    var herfList = CustomMethod.GetInfoFroma(list[index]);
                    if (herfList == null || herfList.Count < 2)
                    {
                        CustomMethod.WriteLog("天上掉馅饼：没有获取到herf连接数据");
                        continue;
                    }
                    //-----------------------------获取商品分类-------------------------
                    string regex = @" <div class=""sc_sj"">[\s\S]*?</div>";
                    product.ProductTypeId = pEnum.GetProductTypeId(list[index], regex, typeof(ProductTypeEnum.tsdxbType),0);
                   //------------------------------------------------------------------
                    string detailUrl = "http://www.tsdxb.com/" + herfList[0];
                    string detailText = CustomMethod.GetWebHTML(detailUrl);
                    string urlRegex = @"<div class=""con_left_cp con_left_cp1"">[\s\S]*?</a></div>";
                    var urlContent = CustomMethod.GetInfoByRegex(urlRegex, detailText, 0);
                    if (urlContent == null || urlContent.Count < 1)
                    {
                        CustomMethod.WriteLog("天上掉馅饼：详细页面中未获取商品链接区域");
                        continue;
                    }
                    var buyUrlList = CustomMethod.GetInfoFroma(urlContent[0]);
                    if (buyUrlList == null || buyUrlList.Count < 4)
                    {
                        CustomMethod.WriteLog("天上掉馅饼：详细页面中未获取商品链接");
                        continue;
                    }
                    string buyUrl = "http://www.tsdxb.com/" + buyUrlList[0];
                    string productUrl = "";
                    product.Plink = CustomMethod.GetUrlByCurrentUrl(buyUrl, ref productUrl);
                    if (product.Plink == "")
                    {
                        if (productUrl == "")
                        {
                            CustomMethod.WriteLog("天上掉馅饼：没有匹配出商品链接");
                        }
                        continue;
                    }
                    product.Memo = productUrl;
                    string imgRegex = @"<div class=""r_bk_imgn"">[\s\S]*?</div>";
                    var imgList = CustomMethod.GetInfoByRegex(imgRegex, detailText, 0);
                    if (imgList == null || imgList.Count < 1)
                    {
                        string imgText = CustomMethod.GetHtmlByHttpHelper(product.Plink);
                        continue;
                    }
                    else
                    {
                        product.ImgUrl = CustomMethod.GetImgUrl(imgList[0], "天上掉馅饼");
                        if (product.ImgUrl == "")
                        {
                            CustomMethod.WriteLog("天上掉馅饼：没有匹配出商品图片信息");
                            continue;
                        }
                    }
                    string sorRegex = @"<div class=""l_bk"">[\s\S]*?<p>";
                    var sorceContent = CustomMethod.GetInfoByRegex(sorRegex,list[index],0);
                    if (sorceContent.Count >0)
                    {
                        var sorceList = CustomMethod.GetInfoFroma(sorceContent[0]);
                        if (sorceList.Count > 2)
                        {
                            product.Source = sorceList[sorceList.Count - 1];
                        }
                    } 
                    product.Pname = herfList[1].Replace("<span>", "").Replace("</span>", "");
                    string desRegex = @"</a></div>\s+<p>[\s\S]*?<div class=""r_bk"">";
                    var desList = CustomMethod.GetInfoByRegex(desRegex, list[index], 0);
                    if (desList == null || desList.Count < 1)
                    {
                        product.Description = product.Pname;
                    }
                    //获取描述信息
                    else
                    {
                        string pRegex = @"<p itemprop=""description"">[\s\S]*?</p>";
                        var despList = CustomMethod.GetInfoByRegex(pRegex, desList[0], 0);
                        if (despList.Count < 1)
                        {
                            pRegex = @"<p>[\s\S]*?</p>";
                            despList = CustomMethod.GetInfoByRegex(pRegex, desList[0], 0);
                        }
                        string description = "";
                        for (int count = 0; count < desList.Count; count++)
                        {

                            description += Regex.Replace(desList[count], @"<(.[^>]*)>", "") + "|||";
                            if (description.Contains("PS:海淘教程在此"))
                            {
                                product.TypeId = (int)MallsEnumClass.NavigationType.海淘;
                                int endIndex = description.IndexOf("PS");
                                description = description.Substring(0, endIndex);
                            }
                        }
                        product.Description = description;
                    }
                    //获取价格
                    string pricRegex = @"<div class=""fd_rmb_xj""></div>([^<]+)</div>";
                    var pricList = CustomMethod.GetInfoByRegex(pricRegex, list[index], 1);
                    if (pricList != null && pricList.Count > 0)
                    {
                        product.Price = pricList[0];
                    }
                    else
                    {
                        product.Price = "";
                    }
                    product.UpdateTime = DateTime.Now;
                    product.UpdateTimeStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                }
                catch (Exception ex)
                {
                    CustomMethod.WriteLog("天上掉馅饼：" + ex.Message.ToString());
                    continue;
                }
                product.Pname = System.Web.HttpUtility.HtmlEncode(product.Pname);
                pList.Add(product);
            }
            var newList = CustomMethod.GetDistinctProdcuts(pList);
            newList.Reverse();
            return newList;
        }
    }
}
